package com.app.traval.web.rest;

import com.codahale.metrics.annotation.Timed;
import com.app.traval.domain.Opinion;
import com.app.traval.service.OpinionService;
import com.app.traval.web.rest.util.HeaderUtil;
import com.app.traval.web.rest.util.PaginationUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import static org.elasticsearch.index.query.QueryBuilders.*;

/**
 * REST controller for managing Opinion.
 */
@RestController
@RequestMapping("/api")
public class OpinionResource {

    private final Logger log = LoggerFactory.getLogger(OpinionResource.class);
        
    @Inject
    private OpinionService opinionService;
    
    /**
     * POST  /opinions : Create a new opinion.
     *
     * @param opinion the opinion to create
     * @return the ResponseEntity with status 201 (Created) and with body the new opinion, or with status 400 (Bad Request) if the opinion has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @RequestMapping(value = "/opinions",
        method = RequestMethod.POST,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    public ResponseEntity<Opinion> createOpinion(@Valid @RequestBody Opinion opinion) throws URISyntaxException {
        log.debug("REST request to save Opinion : {}", opinion);
        if (opinion.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("opinion", "idexists", "A new opinion cannot already have an ID")).body(null);
        }
        Opinion result = opinionService.save(opinion);
        return ResponseEntity.created(new URI("/api/opinions/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert("opinion", result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /opinions : Updates an existing opinion.
     *
     * @param opinion the opinion to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated opinion,
     * or with status 400 (Bad Request) if the opinion is not valid,
     * or with status 500 (Internal Server Error) if the opinion couldnt be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @RequestMapping(value = "/opinions",
        method = RequestMethod.PUT,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    public ResponseEntity<Opinion> updateOpinion(@Valid @RequestBody Opinion opinion) throws URISyntaxException {
        log.debug("REST request to update Opinion : {}", opinion);
        if (opinion.getId() == null) {
            return createOpinion(opinion);
        }
        Opinion result = opinionService.save(opinion);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert("opinion", opinion.getId().toString()))
            .body(result);
    }

    /**
     * GET  /opinions : get all the opinions.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of opinions in body
     * @throws URISyntaxException if there is an error to generate the pagination HTTP headers
     */
    @RequestMapping(value = "/opinions",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    public ResponseEntity<List<Opinion>> getAllOpinions(Pageable pageable)
        throws URISyntaxException {
        log.debug("REST request to get a page of Opinions");
        Page<Opinion> page = opinionService.findAll(pageable); 
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/opinions");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    /**
     * GET  /opinions/:id : get the "id" opinion.
     *
     * @param id the id of the opinion to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the opinion, or with status 404 (Not Found)
     */
    @RequestMapping(value = "/opinions/{id}",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    public ResponseEntity<Opinion> getOpinion(@PathVariable Long id) {
        log.debug("REST request to get Opinion : {}", id);
        Opinion opinion = opinionService.findOne(id);
        return Optional.ofNullable(opinion)
            .map(result -> new ResponseEntity<>(
                result,
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * DELETE  /opinions/:id : delete the "id" opinion.
     *
     * @param id the id of the opinion to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @RequestMapping(value = "/opinions/{id}",
        method = RequestMethod.DELETE,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    public ResponseEntity<Void> deleteOpinion(@PathVariable Long id) {
        log.debug("REST request to delete Opinion : {}", id);
        opinionService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("opinion", id.toString())).build();
    }

    /**
     * SEARCH  /_search/opinions?query=:query : search for the opinion corresponding
     * to the query.
     *
     * @param query the query of the opinion search
     * @return the result of the search
     */
    @RequestMapping(value = "/_search/opinions",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    public ResponseEntity<List<Opinion>> searchOpinions(@RequestParam String query, Pageable pageable)
        throws URISyntaxException {
        log.debug("REST request to search for a page of Opinions for query {}", query);
        Page<Opinion> page = opinionService.search(query, pageable);
        HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/opinions");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

}
